#!/usr/bin/env python3
"""
数据库初始化脚本
"""

import os
import sys
from app import create_app
from models import db, User, Employee, AttendanceRecord, PayrollRecord
from werkzeug.security import generate_password_hash
from datetime import datetime, date, time
import random

def main():
    """主函数"""
    print("开始初始化数据库...")
    
    # 创建应用
    app = create_app()
    
    with app.app_context():
        try:
            # 删除所有表（如果存在）
            print("删除现有表...")
            db.drop_all()
            
            # 创建所有表
            print("创建数据库表...")
            db.create_all()
            
            # 创建默认管理员用户
            print("创建默认用户...")
            admin_user = User(
                username='admin',
                password_hash=generate_password_hash('admin123'),
                is_active=True
            )
            db.session.add(admin_user)
            db.session.commit()
            print("默认用户创建成功: admin / admin123")
            
            # 创建示例员工数据
            print("创建示例员工数据...")
            employees_data = [
                {
                    'name': '张三',
                    'email': 'zhangsan@company.com',
                    'position': '软件工程师',
                    'department': '技术部',
                    'hire_date': date(2023, 1, 15),
                    'salary': 15000.00,
                    'avatar': 'https://via.placeholder.com/150/6366F1/FFFFFF?text=张',
                    'job_description': '负责前端开发，使用React和TypeScript构建用户界面。'
                },
                {
                    'name': '李四',
                    'email': 'lisi@company.com',
                    'position': '产品经理',
                    'department': '产品部',
                    'hire_date': date(2022, 8, 20),
                    'salary': 18000.00,
                    'avatar': 'https://via.placeholder.com/150/10B981/FFFFFF?text=李',
                    'job_description': '负责产品规划和需求分析，协调开发团队完成产品迭代。'
                },
                {
                    'name': '王五',
                    'email': 'wangwu@company.com',
                    'position': 'UI设计师',
                    'department': '设计部',
                    'hire_date': date(2023, 3, 10),
                    'salary': 12000.00,
                    'avatar': 'https://via.placeholder.com/150/F59E0B/FFFFFF?text=王',
                    'job_description': '负责用户界面设计，创建美观易用的产品界面。'
                }
            ]
            
            employees = []
            for emp_data in employees_data:
                employee = Employee(**emp_data)
                employees.append(employee)
                db.session.add(employee)
            
            db.session.commit()
            print(f"已创建 {len(employees)} 名员工")
            
            # 创建示例考勤记录
            print("创建示例考勤记录...")
            today = date.today()
            
            for employee in employees:
                # 为每个员工创建最近3天的考勤记录
                for days_ago in range(3):
                    record_date = date(today.year, today.month, max(1, today.day - days_ago))
                    
                    # 检查是否已存在该日期的记录
                    existing = AttendanceRecord.query.filter_by(
                        employee_id=employee.id,
                        date=record_date
                    ).first()
                    
                    if existing:
                        continue  # 跳过已存在的记录
                    
                    # 随机生成考勤状态
                    statuses = ['Present', 'Present', 'Late']  # Present概率更高
                    status = random.choice(statuses)
                    
                    clock_in = None
                    clock_out = None
                    
                    if status == 'Present':
                        clock_in = time(9, random.randint(0, 15))  # 9:00-9:15
                        clock_out = time(18, random.randint(0, 30))  # 18:00-18:30
                    elif status == 'Late':
                        clock_in = time(9, random.randint(16, 45))  # 9:16-9:45
                        clock_out = time(18, random.randint(0, 30))  # 18:00-18:30
                    
                    attendance = AttendanceRecord(
                        employee_id=employee.id,
                        date=record_date,
                        status=status,
                        clock_in=clock_in,
                        clock_out=clock_out
                    )
                    db.session.add(attendance)
            
            db.session.commit()
            print("考勤记录创建成功")
            
            # 创建示例工资记录
            print("创建示例工资记录...")
            current_month = datetime.now().strftime('%Y-%m')
            
            for employee in employees:
                bonus = random.randint(0, 3000)  # 0-3000的随机奖金
                deductions = random.randint(0, 500)  # 0-500的随机扣款
                net_pay = employee.salary + bonus - deductions
                
                payroll = PayrollRecord(
                    employee_id=employee.id,
                    pay_period=current_month,
                    base_salary=employee.salary,
                    bonus=bonus,
                    deductions=deductions,
                    net_pay=net_pay
                )
                db.session.add(payroll)
            
            db.session.commit()
            print("工资记录创建成功")
            
            print("\n数据库初始化完成！")
            print("=" * 50)
            print("默认管理员账号: admin / admin123")
            print("数据库类型:", "SQLite" if "sqlite" in app.config['SQLALCHEMY_DATABASE_URI'] else "MySQL")
            print("=" * 50)
            
        except Exception as e:
            print(f"数据库初始化失败: {e}")
            db.session.rollback()
            sys.exit(1)

if __name__ == '__main__':
    main()
